import Request from '@/utils/luch-request/index.js'
import {
	baseUrl,
	baseApiUrl,
	wechatAuthUrl,
	deptId,
	appId,
	signKey
} from '@/utils/constant.js'
import {
	getCurrentPage,
	getCookie
} from '@/utils/util.js'
let signUtil = require('@/utils/signUtil.js')
let sha256 = require('@/utils/crypto.js')

const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('token')
	} catch (e) {}
	return token
}

const http = new Request()
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = baseUrl
	config.header = {
		...config.header
	}
	config.custom = {
		// auth: false, // 是否传token
		// loading: false // 是否使用loading
	}
	config.data = {
		...config.data,
		deptId: deptId,
		appId: appId
	}
	return config
})

http.interceptors.request.use((config) => {
	let timeStamp = new Date().getTime();
	config.params = {
		...config.params,
		deptId: deptId,
		appId: appId
	}
	let sign = getSign(Object.assign({}, config.params, config.data), timeStamp);
	let jwt = uni.getStorageSync('jwt')
	/* 请求之前拦截器。可以使用async await 做异步操作  */
	config.header = {
		...config.header,
		'Timestamp': timeStamp,
		'Sign': sign,
		'Authorization': jwt,
    'x-requested-with': 'XMLHttpRequest'
	}
  // #ifdef H5 || MP-UNIONPAY
  let csrfToken = getCookie('csrf_token')
  // #endif
	// #ifdef MP-WEIXIN
  let JSESSIONID = wx.getStorageSync("LOGIN_JSESSIONID");
  let JSESSIONID_HELPER = wx.getStorageSync("LOGIN_JSESSIONID_HELPER")
  let cookie = { }
  if (!!JSESSIONID) {
  	cookie = {
		'Cookie': 'JSESSIONID=' + JSESSIONID_HELPER + ';csrf_token=zcc'
  	}
  }
	let csrfToken = wx.getStorageSync("LOGIN_CSRFTOKEN_HELPER");
  config.header['cookie'] = cookie.Cookie
	// #endif
	if (config.method == 'POST' && csrfToken) {
		config.header['csrf-token'] = csrfToken
   
	}
	return config
}, (config) => {
	return Promise.reject(config)
})


http.interceptors.response.use((response) => {
	console.log(response.statusCode)
	// #ifdef MP-WEIXIN || MP-UNIONPAY
	saveCsrfToken(response.header)
	// #endif
	if (response.statusCode !== 200) { // 服务端返回的状态码不等于200，则reject()

		return Promise.reject(response)
	}
	return response
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	console.log("response reject:", response)
	if (401 == response.statusCode) {
		let url = getCurrentPage()
		console.log("returnUrl:", url)
		uni.setStorageSync("returnUrl", encodeURIComponent(url))
		// #ifdef MP-UNIONPAY
		console.log("云闪付模式")
		uni.navigateTo({
			url: '/pages/userLoginUnionpay/userLoginUnionpay?returnUrl=' + encodeURIComponent(url)
		})
		return Promise.reject(response)
		// #endif
		if ('wx' == response.data.authType) {
			location.href = wechatAuthUrl + '&returnUrl=' + encodeURIComponent(url)
		} else if ('/index/userReg.html' == response.data.redirectUrl) {
			uni.navigateTo({
				url: '/pages/userReg/userReg?returnUrl=' + encodeURIComponent(url)
			})
		} else if ('account' == response.data.authType) {
			uni.navigateTo({
				url: '/pages/userLogin/userLogin?returnUrl=' + encodeURIComponent(url)
			})
		} else if ('yxlm' == response.data.authType) {
			uni.navigateTo({
				url: '/pages/yxlm/yxlm?returnUrl=' + encodeURIComponent(url)
			})
		}
	}
	if (510 == response.statusCode) {
		location.reload()
	}
	return Promise.reject(response)
})

let saveCsrfToken = function(header) {
  console.log('执行一次')
	var cookie_str;
	for (var key in header) {
		if ('set-cookie' == key.toLowerCase()) {
			cookie_str = header[key];
			break;
		}
	}
	if (null == cookie_str || undefined == cookie_str) {
		return;
	}
	var start = cookie_str.indexOf('csrf_token');
	var end;
	var csrfTokenT;
	while (start > -1) {
		end = cookie_str.indexOf(';', start);
		if (end == -1) {
			end = cookie_str.length;
		}
		csrfTokenT = cookie_str.substring(start + 'csrf_token'.length + 1, end);
		if (null != csrfTokenT && 'null' != csrfTokenT && '' != csrfTokenT && undefined != csrfTokenT) {
			wx.setStorageSync("LOGIN_CSRFTOKEN_HELPER", csrfTokenT);
			console.log('CSRF ' + wx.getStorageSync("LOGIN_CSRFTOKEN_HELPER"));
			return;
		}
		start = cookie_str.indexOf('csrf_token', end);
	}
}

let getSign = function(params, timeStamp) {
	if (null == params || undefined == params) {
		params = {};
	}
	params.timestamp = timeStamp;
	var requestStr = signUtil.paramsToRequestStr(params);
	delete params.timestamp;
	// console.log("待签名串：" + requestStr + signKey);
	var sign = sha256.hex_sha256(requestStr + signKey).toString();
	return sign;
}

export {
	http
}
